package com.bbf.redis.controller;

import com.bbf.redis.model.StringToRedisModel;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 测试Controller
 * @author BBF
 */
@RestController
@RequestMapping(value = "/redis")
public class WebTestController {
  @Resource
  private StringToRedisModel stringToRedisModel;
  private static final String KEYTEMPLETE = "redis:mvc:key:%s";

  /**
   * 写入Redis
   * @param key 待写入的key
   * @param msg 待写入的信息
   * @return 实际存入redis的完整key
   */
  @RequestMapping(value = "/set/{key}/{msg}", method = RequestMethod.GET,
      produces = "application/json;charset=UTF-8")
  public String setRedisValue(@PathVariable(name = "key") String key,
                              @PathVariable(name = "msg") String msg) {
    String k = String.format(KEYTEMPLETE, key);
    stringToRedisModel.set(k, msg, 600);
    return k;
  }

  /**
   * 读取Redis
   * @param key 待读取的key
   * @return 读取的信息
   */
  @RequestMapping(value = "/get/{key}", method = RequestMethod.GET,
      produces = "application/json;charset=UTF-8")
  public String getRedisValue(@PathVariable(name = "key") String key) {
    return stringToRedisModel.get(String.format(KEYTEMPLETE, key));
  }
}
